package org.example.myleet.p405;

public class Solution {

    private static final char[] HEX_CHAR = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public String toHex(int num) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; ++i) {
            //每4位转换成一个16进制的字符，然后整体向右移4位，做8次就可以将整个32位整数分析完
            int bit = num & 0b1111;
            sb.insert(0, HEX_CHAR[bit]);
            num = num >> 4;
        }
        //最后去除前导0
        int c0 = sb.charAt(0);
        while (c0 == '0' && sb.length() > 1) {
            sb.deleteCharAt(0);
            c0 = sb.charAt(0);
        }
        return sb.toString();
    }
}
